package com.apes.framework.jpa.generator;

import com.apes.framework.util.JpaUtil;
import com.apes.framework.jpa.generator.model.Sequence;
import com.apes.framework.util.ReflectUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：Generator Util
 *
 * @author xul
 * @create 2019-03-01 10:25
 */
public class GeneratorUtil {
    private static Map<String, Sequence> sequences = new HashMap<>();
    private static boolean initFlag = false;

    public static Sequence getSequence(String sequenceId) {
        if (!initFlag) {
            initFlag = true;
            JpaUtil.getAllDomainType().forEach(domainTypeName -> {
                Class domainType = ReflectUtil.getClass(domainTypeName);
                ApesGenerators idGenerators = ReflectUtil.getAnnotation(domainType, ApesGenerators.class);
                if (idGenerators != null) {
                    for (ApesGenerator generator : idGenerators.value()) {
                        addSequence(generatorToSequence(generator));
                    }
                }
                ReflectUtil.doWithFields(domainType, descriptor -> {
                    ApesGenerator generator = ReflectUtil.getAnnotation(domainType, descriptor.getName(), ApesGenerator.class);
                    addSequence(generatorToSequence(generator));
                }, descriptor -> ReflectUtil.getAnnotation(domainType, descriptor.getName(), ApesGenerator.class) != null);
            });
        }
        Sequence sequence = sequences.get(sequenceId);
        if (sequence == null) throw new RuntimeException("Sequence: " + sequenceId + " not exits.");
        return sequences.get(sequenceId);
    }

    public static void addSequence(Sequence sequence) {
        sequences.put(sequence.getCode(), sequence);
    }

    public static void addSequences(List<Sequence> sequences) {
        sequences.stream().forEach(sequence -> addSequence(sequence));
    }

    public static void removeSequence(String sequenceId) {
        sequences.remove(sequenceId);
    }

    /**
     * 功能：通过注解创建序列实体
     */
    private static Sequence generatorToSequence(ApesGenerator generator) {
        Sequence sequence = new Sequence();
        sequence.setCode(generator.code());
        sequence.setName(generator.name());
        sequence.setImplementation(generator.implementation().toString());
        sequence.setNumberIncrement(generator.increment());
        sequence.setNumberNext(generator.numberNext());
        sequence.setPadding(generator.padding());
        sequence.setPrefix(generator.prefix());
        sequence.setSuffix(generator.suffix());
        sequence.setUseDateRange(generator.useDateRange());
        return sequence;
    }
}
